package com.hema.auction.fragment;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hema.auction.R;
import com.hema.auction.activity.GoodsDetailsActivity;
import com.hema.auction.adapter.IndexAuctionAdapter;
import com.hema.auction.base.BaseFragment;
import com.hema.auction.bean.GoodsInfo;
import com.hema.auction.http.HttpTag;
import com.hema.auction.http.biz.HttpManager;
import com.hema.auction.utils.Constant;
import com.hema.auction.widget.GridSpaceItemDecoration;
import com.hema.auction.widget.view.EmptyView;
import com.hema.auction.widget.view.MyLoadMoreView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.Call;

import static com.hema.auction.http.HttpTag.TAG_GET_NEWST_ORDERS;


/**
 * 描述:
 * 作者:john
 */
public class IndextabFragment extends BaseFragment {

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    private IndexAuctionAdapter indexAuctionAdapter;
    private List<GoodsInfo> goodsInfos = new ArrayList<>();
    private int tabIndex, collectIndex;
    private boolean isRefresh = true;
    private SwipeRefreshLayout refreshLayout;
    private EmptyView emptyView;

    public static IndextabFragment newInstance(int position) {
        Bundle bundle = new Bundle();
        bundle.putInt(Constant.EXTRA_POSITION, position);
        IndextabFragment fragment = new IndextabFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_index_tab;
    }

    public void refreshLayout(SwipeRefreshLayout refreshLayout) {
        this.refreshLayout = refreshLayout;
    }

    @Override
    protected void init() {
        super.init();
        tabIndex = getArguments().getInt(Constant.EXTRA_POSITION);
        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 2);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new GridSpaceItemDecoration(getActivity(), 1));
        indexAuctionAdapter = new IndexAuctionAdapter(goodsInfos);
        indexAuctionAdapter.setLoadMoreView(new MyLoadMoreView());
        indexAuctionAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putParcelable(Constant.EXTRA_GOOD_INFO, indexAuctionAdapter.getData().get(position));
                intentTo(GoodsDetailsActivity.class, bundle);
            }
        });
        indexAuctionAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (isLogin) {
                    collectIndex = position;
                    showProgressDialog();
                    if (indexAuctionAdapter.getData().get(position).getIsCollected() == 0) {
                        HttpManager.getInstance(getActivity()).collectGood(indexAuctionAdapter.getData().get(position).getId(), IndextabFragment.this);
                    } else {
                        HttpManager.getInstance(getActivity()).delCollection(indexAuctionAdapter.getData().get(position).getId(), IndextabFragment.this);
                    }

                } else {
                    goLogin();
                }
            }
        });
//        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                super.onScrolled(recyclerView, dx, dy);
//                LogUtils.i("--------是否能向下滚动 = " + !recyclerView.canScrollVertically(0));
//                scrollView.setChildCanScrollBottom(!recyclerView.canScrollVertically(0));
//            }
//
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//            }
//        });
        recyclerView.setAdapter(indexAuctionAdapter);
        getData();
    }


    private void getData() {
        switch (tabIndex) {
            case 0://正在热拍
                if (emptyView == null) {
                    emptyView = new EmptyView(getActivity());
                    emptyView.setViewType(EmptyView.OTHER);
                    indexAuctionAdapter.setEmptyView(emptyView);
                }
                HttpManager.getInstance(getActivity()).getHotGoods(pageIndex, pageSize, this);
                indexAuctionAdapter.setOnLoadMoreListener(this, recyclerView);
                break;
            case 1://我的竞拍
                if (emptyView == null) {
                    emptyView = new EmptyView(getActivity());
                    emptyView.setViewType(EmptyView.I_AUCTION);
                    indexAuctionAdapter.setEmptyView(emptyView);
                }
                HttpManager.getInstance(getActivity()).getSelfSales(pageIndex, pageSize, this);
                break;
            case 2://我的收藏
                if (emptyView == null) {
                    emptyView = new EmptyView(getActivity());
                    emptyView.setViewType(EmptyView.FOCUS);
                    indexAuctionAdapter.setEmptyView(emptyView);
                }
                HttpManager.getInstance(getActivity()).getCollections(pageIndex, pageSize, this);
                indexAuctionAdapter.setOnLoadMoreListener(this, recyclerView);
                break;
        }
    }

    public RecyclerView getRecyclerView(){
        return recyclerView;
    }

    public void refresh() {
        isRefresh = true;
        pageIndex = 1;
        getData();
    }

    @Override
    protected void onLoadMore() {
        super.onLoadMore();
        isRefresh = false;
        pageIndex++;
        getData();
    }

    @Override
    protected void onSuccess(HttpTag httpTag, Call call, JSONObject result) {
        super.onSuccess(httpTag, call, result);
        switch (httpTag) {
            case TAG_GET_HOT_GOODS:
                try {
                    if (result.getInt("errcode") == 0) {
                        List<GoodsInfo> goodsInfos = new Gson().fromJson(result.getJSONArray("data").toString(), new TypeToken<List<GoodsInfo>>() {
                        }.getType());
                        if (isRefresh) {
                            indexAuctionAdapter.setNewData(goodsInfos);
                            if (goodsInfos.size() < pageSize) {
                                indexAuctionAdapter.setEnableLoadMore(false);
                            } else {
                                indexAuctionAdapter.setEnableLoadMore(true);
                            }
                        } else {
                            indexAuctionAdapter.addData(goodsInfos);
                            indexAuctionAdapter.loadMoreComplete();
                            if (goodsInfos.size() < pageSize) {
                                indexAuctionAdapter.loadMoreEnd();
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_GET_SELF_SALES:
                try {
                    if (result.getInt("errcode") == 0) {
                        List<GoodsInfo> goodsInfos = new Gson().fromJson(result.getJSONArray("data").toString(), new TypeToken<List<GoodsInfo>>() {
                        }.getType());
                        if (isRefresh) {
                            indexAuctionAdapter.setNewData(goodsInfos);
                            if (goodsInfos.size() < pageSize) {
                                indexAuctionAdapter.setEnableLoadMore(false);
                            } else {
                                indexAuctionAdapter.setEnableLoadMore(true);
                            }
                        } else {
                            indexAuctionAdapter.addData(goodsInfos);
                            indexAuctionAdapter.loadMoreComplete();
                            if (goodsInfos.size() < pageSize) {
                                indexAuctionAdapter.loadMoreEnd();
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_COLLECT_GOOD:
                try {
                    if (result.getInt("errcode") == 0) {
                        indexAuctionAdapter.getData().get(collectIndex).setIsCollected(1);
                        indexAuctionAdapter.notifyDataSetChanged();
                    }
//                    showToastSafe(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_GET_COLLECTIONS:
                try {
                    if (result.getInt("errcode") == 0) {
                        List<GoodsInfo> goodsInfos = new Gson().fromJson(result.getJSONArray("data").toString(), new TypeToken<List<GoodsInfo>>() {
                        }.getType());
                        if (isRefresh) {
                            indexAuctionAdapter.setNewData(goodsInfos);
                            if (goodsInfos.size() < pageSize) {
                                indexAuctionAdapter.setEnableLoadMore(false);
                            } else {
                                indexAuctionAdapter.setEnableLoadMore(true);
                            }
                        } else {
                            indexAuctionAdapter.addData(goodsInfos);
                            indexAuctionAdapter.loadMoreComplete();
                            if (goodsInfos.size() < pageSize) {
                                indexAuctionAdapter.loadMoreEnd();
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_DEL_COLLECT:
                try {
                    if (result.getInt("errcode") == 0) {
                        if (tabIndex == 2) {
                            indexAuctionAdapter.remove(collectIndex);
                        } else {
                            indexAuctionAdapter.getData().get(collectIndex).setIsCollected(0);
                            indexAuctionAdapter.notifyDataSetChanged();
                        }
                    }
//                    showToastSafe(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }


    @Override
    protected void onError(HttpTag httpTag, Call call, IOException e) {
        super.onError(httpTag, call, e);
        if (httpTag == TAG_GET_NEWST_ORDERS) {
        }
    }

    @Override
    protected void onFinish(HttpTag httpTag) {
        super.onFinish(httpTag);
        if (refreshLayout != null)
            refreshLayout.setRefreshing(false);
        isRefresh = false;
    }
}
